package cate.game.server.configuration.dao;

import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import easy.java.practice.errorcode.EcException;
import easy.mongo.anno.MgMapField;
import org.bson.BsonValue;
import org.bson.Document;

import java.util.Optional;

public abstract class MgStrKeyDao<T> extends MgRepo<T, String> {

    @Override
    protected Class<T> getEntityClass() {
        return null;
    }

    @Override
    protected <S extends T> void handleAutoId(S entity, BsonValue bv) {
    }

    @Override
    public Optional<T> findById(String uid) {
        FindIterable<Document> fi = collection.find(Filters.eq(MgMapField.ID, uid));
        Document doc = fi.first();
        if(doc == null) {
            return Optional.empty();
        }
        try {
            T entity;
            if(null != getEntityClass()) {
                entity = getMapper().decode(doc, getEntityClass());
            } else {
                entity = (T) getMapper().decode(doc);
            }
            return Optional.of(entity);
        } catch (Exception e) {
            throw new EcException(e);
        }
    }

    @Override
    public void deleteById(String uid) {
        collection.deleteOne(Filters.eq(MgMapField.ID, uid));
    }

}
